package com.moons.demo.aicamera.facerecognition.adapter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.moons.demo.aicamera.facerecognition.R;
import com.moons.demo.aicamera.facerecognition.config.DemoConfig;
import com.moons.demo.aicamera.facerecognition.constants.Common;
import com.moons.demo.aicamera.facerecognition.model.UserFace;
import com.moons.demo.aicamera.facerecognition.util.FaceDataUtil;
import com.moons.demo.aicamera.facerecognition.util.ThreadPool.ThreadPoolManager;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

public class RegedFaceRecyclerViewAdapter extends RecyclerView.Adapter<RegedFaceRecyclerViewAdapter.ViewHolder> {
    private static final String TAG = "RegedFaceRecyclerViewAdapter";
    private final LayoutInflater mLayoutInflater;
    private final Context mContext;

    private List<UserFace> mUserFaceList;

    private UIHandler mUIHandler;

    public RegedFaceRecyclerViewAdapter(Context context) {
        mContext = context;
        mLayoutInflater = LayoutInflater.from(context);
        mUserFaceList = new ArrayList<>();
        mUIHandler = new UIHandler(this);
    }

    public static final int NOTIFY_ITEM_REMOVED = 0;

    private static class UIHandler extends Handler {

        private final WeakReference<RegedFaceRecyclerViewAdapter> mWeakReference;

        UIHandler(RegedFaceRecyclerViewAdapter mRegedFaceRecyclerViewAdapter) {
            mWeakReference = new WeakReference<>(mRegedFaceRecyclerViewAdapter);
        }

        @SuppressLint("LongLogTag")
        @Override
        public void handleMessage(Message message) {
            final RegedFaceRecyclerViewAdapter mRegedFaceRecyclerViewAdapter = mWeakReference.get();

            if (mRegedFaceRecyclerViewAdapter == null) {

                Log.e(TAG, "handlerMessage: mRegedFaceRecyclerViewAdapter may be destroyed");

                return;
            }

            switch (message.what) {
                case NOTIFY_ITEM_REMOVED:
                    mRegedFaceRecyclerViewAdapter.mUserFaceList.remove(message.arg1);
                    mRegedFaceRecyclerViewAdapter.notifyItemRemoved(message.arg1);

                    break;


                default:

            }


        }

    }


    public void updateData(List<UserFace> userFaceList) {
        mUserFaceList.clear();
        mUserFaceList.addAll(userFaceList);
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new ViewHolder(mLayoutInflater.inflate(R.layout.regface_list_item, parent, false));

    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, final int position) {

        if (position >= mUserFaceList.size()) {
            return;
        }
        final UserFace userFace = mUserFaceList.get(position);

        Glide.with(mContext).load(new File(DemoConfig.FacePicPath + userFace.getPictureId() + ".jpg"))
                .diskCacheStrategy(DiskCacheStrategy.NONE)
                .skipMemoryCache(true)
                .error(R.mipmap.ic_launcher_round)
                .into(holder.iv_user_face);
        holder.tv_id.setText(String.format(Locale.getDefault(), "%d", userFace.getId()));
        holder.tv_name.setText(String.format(Locale.getDefault(), "%s", userFace.getName()));

        String gender = "未知";
        switch (userFace.getGerder()) {
            case Common.Genger.FEMALE:
                gender = "女";
                break;
            case Common.Genger.MALE:
                gender = "男";
                break;
            default:
                gender = "未知";
        }

        holder.tv_gender.setText(gender);


        holder.tv_age.setText(String.format(Locale.getDefault(), "%d", userFace.getAge()));
        holder.bt_delete_item.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new MaterialDialog.Builder(mContext)
                        .iconRes(R.drawable.ic_action_warning)
                        .title("请注意")
                        .content("是否要删除此用户数据?")
                        .positiveText("确定")
                        .negativeText("取消")
                        .onPositive(new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {

                                ThreadPoolManager.getInstance().getBackgroundExecutorService().execute(new Runnable() {
                                    @Override
                                    public void run() {
                                        FaceDataUtil.getInstance().delete(userFace);
                                        Message message = new Message();
                                        message.what = NOTIFY_ITEM_REMOVED;
                                        message.arg1 = position;

                                        mUIHandler.sendMessageDelayed(message, 50);
                                    }
                                });


                            }
                        })
                        .show();
            }
        });

    }

    @Override
    public int getItemCount() {
        return mUserFaceList.size();
    }

    class ViewHolder extends RecyclerView.ViewHolder {
        ImageView iv_user_face;
        TextView tv_id;
        TextView tv_name;
        TextView tv_age;
        TextView tv_gender;

        ImageButton bt_delete_item;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            iv_user_face = itemView.findViewById(R.id.iv_user_face);
            tv_id = itemView.findViewById(R.id.tv_id);
            tv_name = itemView.findViewById(R.id.tv_name);
            tv_age = itemView.findViewById(R.id.tv_age);
            tv_gender = itemView.findViewById(R.id.tv_gender);

            bt_delete_item = itemView.findViewById(R.id.bt_delete_item);


        }
    }
}
